package cn.intozhou.zlive;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.intozhou.zlive.utils.DbManager;

public class RoomServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8266020170983794217L;
	private static final String PARAM_USER_ID = "userId";
	private static final String PARAM_USER_AVATAR = "userAvatar";
	private static final String PARAM_USER_NAME = "userName";
	private static final String PARAM_LIVE_COVER = "liveCover";
	private static final String PARAM_LIVE_TITLE = "liveTitle";

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doGet(req, resp);
		String userId = req.getParameter(PARAM_USER_ID);
		if (userId == null) {
			userId = "";
		}

		String userAvatar = req.getParameter(PARAM_USER_AVATAR);
		if (userAvatar == null) {
			userAvatar = "";
		}

		String userName = req.getParameter(PARAM_USER_NAME);
		if (userName == null) {
			userName = "";
		}

		String liveCover = req.getParameter(PARAM_LIVE_COVER);
		if (liveCover == null) {
			liveCover = "";
		}

		String liveTitle = req.getParameter(PARAM_LIVE_TITLE);
		if (liveTitle == null) {
			liveTitle = "";
		}

		try {
			// 插入一条房间信息
			String insertRoomSql = "INSERT INTO `room_info`(`user_id`, `user_name`, `user_avatar`, `live_cover`, `live_title`, `watcher_nums`) VALUES ("
					+ "0" + "," + userId + "," + userName + "," + userAvatar + "," + liveCover + "," + liveTitle + ","
					+ "0" + ")";
			boolean isSucc = DbManager.getInstance().execute(insertRoomSql);
			if (isSucc) {
				String selectRoomIdSql = "SELECT `room_id` FROM `room_info` WHERE user_id=" + userId;
				ResultSet set = DbManager.getInstance().query(selectRoomIdSql);
				if (set != null && !set.wasNull()) {
					int roomId = 0;
					while (set.next()) {
						roomId = set.getInt("room_id");
					}
					resp.getWriter().println("roomId=" + roomId);
				}
			}
		} catch (SQLException e) {
			resp.getWriter().print(e.getMessage());
		}
	}

}
